package com.poizon.infrastructure.center.config.starter.nacos;


import cn.hutool.core.lang.Assert;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.poizon.infrastructure.center.config.core.event.listener.AbstractChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * nacos依赖存在则自动加载
 */
@Slf4j
@ConditionalOnClass(value = ConfigService.class)
public class NacosAutoConfig {
    @Bean
    public NacosChangeListener nacosChangeListener(AbstractChangeListener abstractChangeListener) {
        log.info(">初始化nacos配置变更监听器");
        return new NacosChangeListener(abstractChangeListener);
    }

    /**
     * nacos配置服务注册
     */
    @Bean
    public ConfigService nacosConfigService(Environment environment) throws NacosException {
        log.info(">初始化nacos-ConfigService");

        // todo:
        String serverAddr = environment.getProperty("nacos.config.server-addr");
        Assert.notBlank(serverAddr,"请先配置nacos地址");
        Properties properties = new Properties();
        properties.put("serverAddr", serverAddr);
        ConfigService configService = NacosFactory.createConfigService(properties);
        return configService;
    }

    /**
     * nacos配置监听器
     */
    @Bean
    public NacosChangeListenerRegister nacosChangeListenerRegister(
            ConfigService configService,
            NacosChangeListener configChangeListener,
            Environment environment
    ) {
        log.info(">初始化nacos配置变更监听器注册器");
        return new NacosChangeListenerRegister(configService, configChangeListener, environment);
    }
}
